<?php

use org\RedisRanking\DummyDayDataSource;
use org\RedisRanking\Ranking\DailyRanking;
use org\RedisRanking\RankingManger;
use think\Db;
use think\facade\Config;
use think\facade\Log;
use think\facade\Request;

/**
 * 获取排行榜
 * @return array
 */
function get_top_vod_data_list($limit = 20)
{
    $top_list_key = get_redis_cid_ranking_list($limit,"top");

    $vod_list = model('vod')->whereIn('id',array_keys($top_list_key))->field("id as vid,type_id as cid,vod_name,vod_sub,vod_en,vod_letter,vod_serial,vod_class,vod_remarks,vod_pic,vod_actor,vod_director,vod_blurb,vod_area,vod_lang,vod_year,vod_score,vod_custom_sort,vod_content,vod_play_from,vod_play_url,vod_play_note,vod_skip_time,vod_time")->limit(20)->cache()->select();
    foreach ($vod_list as $key =>  $item) {
        $vod_list[$key]['vod_play_list'] = [];
        if (!empty($item['vod_play_from'])) {
//                        $vod_list[$key]['vod_play_list'] = mac_api_play_list($item['vod_play_from'], $item['vod_play_url'],$item['vod_play_note']);
        }
        unset($vod_list[$key]['vod_play_from']);
        unset($vod_list[$key]['vod_play_note']);
        unset($vod_list[$key]['vod_play_url']);
    }

    $vod_list2 = [];
    if (is_array($top_list_key)) {
        foreach ($top_list_key as $id => $value) {
            foreach ($vod_list as  $item2) {
                if ($id == $item2['vid']) {
                    $item2['click'] = $value;
                    $vod_list2[] = $item2;
                }
            }
        }
    }
    return $vod_list2;
}

/**
 * 添加排行榜数据
 * @param int $vid 视频id
 * @param string $ranking_name 排行榜类型
 * @return string
 */
function add_redis_cid_ranking ($vid = 0,$ranking_name = ""){
    $rankingManager = (new RankingManger())->setDataSource(new DummyDayDataSource())->setRankingClasses([DailyRanking::class])->setRankingName($ranking_name)->init();
    return $rankingManager->dailyRanking->add($vid,1);
}


/**
 * 从redis获取排行榜数据
 * @param int $limit 条数
 * @param string $ranking_name 排行榜标识
 * @return array
 * @throws
 */
function get_redis_cid_ranking_list ($limit = 10,$ranking_name = ""){
    $rankingManager = (new RankingManger())->setDataSource(new DummyDayDataSource())->setRankingClasses([DailyRanking::class])->setRankingName($ranking_name)->init();
    return $rankingManager->dailyRanking->top($limit);
}

function echo_live_content ($value) {
    $content = "";
    foreach ($value as $item) {
        $content .= implode(",",$item) . "\r\n";
    }
    return $content;
}

function mac_str_correct($str,$from,$to)
{
    return htmlspecialchars_decode(str_replace($from,$to,$str));
}

/**
 * 解析所有播放列表
 * @param $vod_play_from 来源
 * @param $vod_play_url 播放地址
 * @param $vod_play_note 备注信息
 * @return array
 */
function mac_play_list($vod_play_from,$vod_play_url,$vod_play_note = '')
{
    $vod_play_from_list = [];
    $vod_play_url_list = [];
    $vod_play_note_list = [];

    if(!empty($vod_play_from)) {
        $vod_play_from_list = explode('$$$', $vod_play_from);
    }
    if(!empty($vod_play_url)) {
        $vod_play_url_list = explode('$$$', $vod_play_url);
    }
    if(!empty($vod_play_note)) {
        $vod_play_note_list = explode('$$$', $vod_play_note);
    }

    $res_list = [];
    foreach($vod_play_from_list as $key => $v){
        if (empty($vod_play_url_list)) {
            return  $res_list;
        }

        $urls = mac_play_list_one($vod_play_url_list[$key]);
        $note = "";
        if (array_key_exists($key,$vod_play_note_list)){
            $note = $vod_play_note_list[$key];
        }
        $res_list[$key + 1] = [
            'sid' => $key + 1,
            'from' => $v,
            'url' => $vod_play_url_list[$key],
            'note' => $note,
            'limit' => count($urls),
            'urls' => $urls,
        ];
    }
    return $res_list;
}

/**
 * 播放列表
 * @param $vid 视频id
 * @param $vod_play_from
 * @param $vod_play_url
 * @param string $vod_play_note
 * @param int $vod_custom_sort
 * @return array
 */
function mac_api_play_list($vid,$vod_play_from,$vod_play_url,$vod_play_note = '',$vod_custom_sort = 0,$type = '')
{
    $vod_play_from_list = [];
    $vod_play_url_list = [];
    $vod_play_note_list = [];

    if(!empty($vod_play_from)) {
        $vod_play_from_list = explode('$$$', $vod_play_from);
    }
    if(!empty($vod_play_url)) {
        $vod_play_url_list = explode('$$$', $vod_play_url);
    }
    if(!empty($vod_play_note)) {
        $vod_play_note_list = explode('$$$', $vod_play_note);
    }

    $collect_list = model('collect')->field('collect_tag,is_p2p,collect_name,collect_tv_filter,qrcode_url,jiexi_urls')->order('sort DESC,id DESC')->cache()->select();

    $res_list = [];
    foreach($vod_play_from_list as $key => $play_from){
        $urls = mac_play_list_one($vod_play_url_list[$key]);

        $note = "";
        $qrcode_url = "";
        $jiexi_urls = "";
        $is_p2p = 0;
        $jiexi_count = 0;

        if (array_key_exists($key,$vod_play_note_list)){
            $note = $vod_play_note_list[$key];
        }

        if (empty($note)) {
            foreach ($collect_list as $collect) {
                if (!empty($collect['collect_tag']) && $collect['collect_tag'] == $play_from) {
                    $note = $collect['collect_name'];
                    $qrcode_url = $collect['qrcode_url'];
                    $jiexi_urls = $collect['jiexi_urls'];
                    $is_p2p = $collect['is_p2p'];
                }
            }
        }

        //解析接口
        if (!empty($jiexi_urls) && ($type == "mobile" || $type == "tv")){
            $jiexi_key = 0;
            foreach ($urls as $key2 => $item2) {
                $urls[$key2]['url'] = url("/p/" . $vid . "/" . $play_from . "/" . $jiexi_key += 1,null,"html",true);
            }
        }

        // 如果tv有二维码则不显示播放地址
        if (substr($qrcode_url,0,4) == 'http' && $type == 'tv') {
            $urls = [];
        }else{
            $qrcode_url = "";
        }

        $jiexi_urls = explode("\r",$jiexi_urls);
        foreach ($jiexi_urls as $jiexi) {
            if (!empty($jiexi)) {
                $jiexi_count += 1;
            }
        }

        $res_list[] = [
            'sid' => $key + 1,
            'from' => $play_from,
            'note' => $note,
            'is_p2p' => $is_p2p,
            'jiexi_count' => $jiexi_count,
            'qrcode_url' => $qrcode_url,
            'limit' => count($urls),
            'urls' => $urls,
        ];
    }

    // 排序
    if ($vod_custom_sort == 0) {
        $order_list = [];
        foreach ($collect_list as $collect) {
            if ($type == "tv") {
                if (!empty($collect['collect_tag']) && $collect['collect_tv_filter'] == 1) {
                    foreach ($res_list as $item) {
                        if ($collect['collect_tag'] == $item['from']) {
                            $order_list[] = $item;
                        }
                    }
                }
            }else{
                if (!empty($collect['collect_tag'])) {
                    foreach ($res_list as $item) {
                        if ($collect['collect_tag'] == $item['from']) {
                            $order_list[] = $item;
                        }
                    }
                }
            }
        }
        return $order_list;
    }else {
        return $res_list;
    }
}

function mac_play_list_one($urs = ''){
    $url_list = array();
    try {
        $array_url = explode('#',$urs);
        foreach($array_url as $key => $val){
            if(empty($val)) continue;
            $key += 1;
            list($title, $url) = explode('$', $val);
            if (empty($url) ) {
                $url_list[] = [
                    'name' => '第'.$key.'集',
                    'url' => $title
                ];
            }else{
                $url_list[] = [
                    'name' => $title,
                    'url' => $url,
                ];
            }
        }
    }catch (Exception $e) {
        Log::info($e->getMessage());
    }
    return $url_list;
}

function mac_substring($str, $lenth, $start=0)
{
    $len = strlen($str);
    $r = array();
    $n = 0;
    $m = 0;

    for($i=0;$i<$len;$i++){
        $x = substr($str, $i, 1);
        $a = base_convert(ord($x), 10, 2);
        $a = substr( '00000000 '.$a, -8);

        if ($n < $start){
            if (substr($a, 0, 1) == 0) {
            }
            else if (substr($a, 0, 3) == 110) {
                $i += 1;
            }
            else if (substr($a, 0, 4) == 1110) {
                $i += 2;
            }
            $n++;
        }
        else{
            if (substr($a, 0, 1) == 0) {
                $r[] = substr($str, $i, 1);
            }else if (substr($a, 0, 3) == 110) {
                $r[] = substr($str, $i, 2);
                $i += 1;
            }else if (substr($a, 0, 4) == 1110) {
                $r[] = substr($str, $i, 3);
                $i += 2;
            }else{
                $r[] = ' ';
            }
            if (++$m >= $lenth){
                break;
            }
        }
    }
    return  join('',$r);
}

function mac_like_arr($s)
{
    $tmp = explode(',',$s);
    foreach($tmp as $k=>$v){
        $tmp[$k] = '%'.$v.'%';
    }
    return $tmp;
}


function http_header($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $header = ['User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36']; //设置一个你的浏览器agent的header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);
    if ($sError = curl_error($ch)) {
        die($sError);
    }
    curl_close($ch);

    $result = explode("\r",$result);
    foreach ($result as $item) {
        if (substr(trim($item),0,9) == "location:") {
            return trim(str_replace("location:","",$item));
        }
    }
    return "";
}

/**
 * 获取301地址
 * @param $url
 * @return mixed
 */
function getRealURL($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPGET, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $header = ['User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36']; //设置一个你的浏览器agent的header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);

    $result = explode("\r",$result);
    foreach ($result as $item) {
        if (substr(trim($item),0,9) == "location:") {
            return trim(str_replace("location:","",$item));
        }
    }

    return "";
}

function get_301($url)
{
    $header = get_headers($url,1);
    if (strpos($header[0],'301') || strpos($header[0],'302')) {
        if(is_array($header['location'])) {
            return $header['location'][count($header['location'])-1];
        }else{
            return $header['location'];
        }
    }else {
        return $url;
    }
}

/**
 * GET远程URL
 * @param $url
 * @param array $heads
 * @param string $cookie
 * @return bool|string
 */
function mac_curl_get($url,$heads = array(),$cookie='')
{
    $ch = @curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_POST, 0);

    if(stripos($url,'https') !== false){
        // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    }

    if(!empty($cookie)){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if(count($heads)>0){
        curl_setopt ($ch, CURLOPT_HTTPHEADER , $heads );
    }
    $response = @curl_exec($ch);
    if(curl_errno($ch)){//出错则显示错误信息
        //print curl_error($ch);die;
    }
    curl_close($ch); //关闭curl链接
    return $response;//显示返回信息
}

/**
 * 获取搜索推荐
 * @param $title
 * @param $content
 * @return false|string
 */
function mac_get_tag($title,$content){
//    $url ='http://zhannei.baidu.com/api/customsearch/keywords?title='.rawurlencode($title).rawurlencode(mac_substring(strip_tags($content),200));
//    $data = curl_url($url);
//    if($data['data']) {
//        $json = json_decode($data['data'],true);
//        if($json){
//            $res = $json['result']['res'];
//            if(is_array(['keyword_list'])){
//                $res = $json['result']['res']['keyword_list'];
//                return join(',',$res);
//            }
//        }
//    }
    return false;
}

function mac_rep_pse_syn($pse,$txt)
{
    if(empty($txt)){ $txt=""; }

    $pse = str_replace([chr(13),chr(10)],"",$pse);
    $psearr = explode('#',$pse);

    foreach($psearr as $a){
        if(!empty($a)){
            $one = explode('=',$a);
            $txt = str_replace($one[0],$one[1],$txt);
            unset($one);
        }
    }
    unset($psearr);
    return $txt;
}


function mac_rep_pse_rnd($pse,$txt,$id=0)
{
    if(empty($txt)){ $txt=""; }
    if(empty($id)){
        $id = crc32($txt);
    }
    $pse = str_replace([chr(13),chr(10)],"",$pse);
    $psearr = explode('#',$pse);
    $i=count($psearr)+1;
    $j = mb_strpos($txt,"<br>");


    if ($j==0){ $j=mb_strpos($txt,"<br/>"); }
    if ($j==0){ $j=mb_strpos($txt,"<br />"); }
    if ($j==0){ $j=mb_strpos($txt,"</p>"); }
    if ($j==0){ $j=mb_strpos($txt,"。")+1;}

    if ($j>0){
        $res= mac_substring($txt,$j-1) . $psearr[$id % $i] . mac_substring($txt,mb_strlen($txt)-$j,$j);
    }
    else{
        $res= $psearr[$id % 1]. $txt;
    }
    unset($psearr);
    return $res;
}

function mac_txt_merge($txt,$str)
{
    if(empty($str)){
        return $txt;
    }
    $config = Config::pull("site_config");
    if($config['vod_class_filter'] != '0') {
        if (mb_strlen($str) > 2) {
            $str = str_replace(['片'], [''], $str);
        }
        if (mb_strlen($str) > 2) {
            $str = str_replace(['剧'], [''], $str);
        }
    }
    $txt = mac_format_text($txt);
    $str = mac_format_text($str);
    $arr1 = explode(',',$txt);
    $arr2 = explode(',',$str);
    $arr = array_merge($arr1,$arr2);
    return join(',',array_unique( array_filter($arr)));
}
function mac_format_text($str)
{
    return str_replace(array('/','，','|','、',' ',',,,'),',',$str);
}
/**
 * 跳转
 * @param $url
 * @param int $sec
 */
function mac_jump($url,$sec=0)
{
    echo '<script>setTimeout(function (){location.href="'.$url.'";},'.($sec*1000).');</script><span>暂停'.$sec.'秒后继续  >>>  </span><a href="'.$url.'" >如果您的浏览器没有自动跳转，请点击这里</a><br>';
}

function mac_buildregx($regstr,$regopt)
{
    return '/'.str_replace('/','\/',$regstr).'/'.$regopt;
}

/**
 * 删除一维数组里的多个key
 */
function ZHTUnset(&$data,$keys){
    if($keys!='' && is_array($data)){
        $key = explode(',',$keys);
        foreach ($key as $v)unset($data[$v]);
    }
}

/**
 * 过滤内容
 * @param $arr
 * @param $str
 * @return bool
 */
function mac_array_filter($arr,$str)
{
    if(!is_array($arr)){
        $arr = explode(',',$arr);
    }
    $arr = array_filter($arr);
    if(empty($arr)){
        return false;
    }
    $new_str = str_replace($arr,'*',$str);
    return $new_str != $str;
}

/**
 * 输出时间 带颜色
 */
function mac_day($time = '',$f='',$c='#FF0000')
{
    if(empty($time)) { return ''; }
    if(is_numeric($time)){
        $time = date('Y-m-d H:i:s',$time);
    }
    $now = date('Y-m-d',time());
    if($f == 'color' && strpos(','.$time,$now)>0){
        return '<font color="' .$c. '">' .$time. '</font>';
    }
    return  $time;
}

function mac_echo($str)
{
    echo $str.'<br>';
    ob_flush();flush();
}

function mac_get_mid_text($data)
{
    $arr = [1=>'视频',2=>'文章',3=>'专题',4=>'评论',5=>'留言',6=>'用户中心',7=>'自定义页面',8=>'明星',9=>'角色'];
    return $arr[$data];
}

/**
 * 判断
 * @param $key
 * @param $value 被比较值
 * @param $html 输出的字符
 * @return string
 */
function eq_site_config($key,$value,$html)
{
    $config = Config::pull("site_config");
    if (array_key_exists($key,$config))
    {
        if ($config[$key] == $value)
        {
            return $html;
        }else {
            return "";
        }
    }else {
        return "";
    }
}

function in_site_config($key,$value,$html)
{
    $config = Config::pull("site_config");
    if (array_key_exists($key,$config))
    {
        if (empty($config[$key])) return "";
        $values = explode(",",$config[$key]);
        foreach ($values as $item) {
            if ($item == $value) return $html;
        }
        return "";
    }else {
        return "";
    }
}

/**
 * 获取站点配置
 * @param $key
 * @return mixed|string
 */
function get_site_config($key)
{
    $config = Config::pull("site_config");
    if (array_key_exists($key,$config))
    {
        return $config[$key];
    }else {
        return "";
    }
}


/**
 * 获取http状态码
 * @param $url
 * @return mixed
 */
function get_http_code($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($curl);
    $return = curl_getinfo($curl);
    curl_close($curl);
    return $return;
}
/**
 * 获取站点信息
 */
function getSystem()
{
    return Config::pull("site_config");
}

/**
 * 显示标签html
 * @param string $tags
 * @return string
 */
function showTags($tags = '')
{
    if (empty($tags)) return "";
    $tags = explode(",", $tags);
    $str = '';
    if (count($tags) > 0) {
        foreach ($tags as $tag) {
            $str .= '<a class="btn btn-light mr-2 disabled opacity-1">' . $tag . '</a>';
        }
    }
    return $str;
}

/**
 * 判断是否移动端域名
 * @param string $prefix
 * @return bool
 */
function isMobileDomain($prefix = 'm')
{
    $domain = str_replace(array('https://', 'http://'), '', strtolower(Request::domain()));
    $domain = explode('.', $domain);
    if (is_array($domain) && $domain[0] == $prefix) {
        return true;
    }
    return false;
}

/**
 * 上传文件到OSS
 * @param string $object 保存文件名
 * @param string $path 本地路径
 * @return bool|string
 */
function uploadFileToOSS($object = '', $path = '')
{

    try {
        $config = Config::pull("aliyun_oss");
        $ossClient = new OssClient($config['key_id'], $config['key_secret'], $config['endpoint']);
        return $ossClient->uploadFile($config['bucket'], $object, $path);
    } catch (OssException $e) {
        return $e->getMessage();
    }
}


/**
 * 获取分类所有子分类
 * @param $type
 * @param $pid
 * @param $limit
 * @return array|bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_category_children($pid, $limit, $is_home)
{
    $where = [];
    if ($pid != -1) {
        $where[] = ['pid', 'eq', $pid];
    }

    if ($is_home == 1) {
        $where[] = ['is_home', 'eq', 1];
    }

    $model = Db::name('category')->where($where);
    if ($limit != 0) {
        $model = $model->limit($limit);
    }

    $children = $model->order(['sort' => 'DESC'])->select();

    return array2tree($children);
}

/**
 * 根据分类ID获取內容列表（包括子分类）
 * @param int $cid 分类ID
 * @param int $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'content', 'thumb', 'reading', 'create_time'], (array)$filed);
    $map = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'create_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'create_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int $pid
 * @param int $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);

        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                if (!array_key_exists($child_key_name, $temp)) {
                    $temp[$child_key_name] = [];
                }
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
                        delete_dir_file($dir_name . DIRECTORY_SEPARATOR . $item);
                    } else {
                        unlink($dir_name . DIRECTORY_SEPARATOR . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}


/**
 * 采集地址
 * @param string $url 远程地址
 * @return mixed
 */
function spider_curl($url = '')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_REFERER, "http://m.360kan.com");
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, curl_headers());
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //允许重定向
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0");//模拟浏览器类型
    curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
    $html = curl_exec($curl);
    if (curl_errno($curl)) {
        print "Error: " . curl_error($curl);
    } else {
        curl_close($curl);
    }

    return $html;
}

/**
 * 随机ip
 * @return array
 */
function curl_headers()
{
    $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
    );

    $rand_key = mt_rand(0, 9);
    $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));


    $headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//    $headers['Accept-Encoding'] = "gzip, deflate";
    $headers['Accept-Language'] = "zh-CN,zh;q=0.8";
    $headers['Cache-Control'] = "no-cache";
    $headers['Connection'] = "keep-alive";
    $headers['Pragma'] = "no-cache";

//    $headers['CLIENT-IP'] = $ip;
//    $headers['X-FORWARDED-FOR'] = $ip;


    $headerArr = array();
    foreach ($headers as $n => $v) {
        $headerArr[] = $n . ':' . $v;
    }
    return $headerArr;
}


/**
 * 请求远程地址
 * @param string $url 地址
 * @param string $cookie
 * @return array
 */
function curl_url($url = '', $param = array(), $cookie = '')
{
    $header[] = "Content-type: application/x-www-form-urlencoded";
    $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

    if (!empty($cookie)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    if (!empty($param) && is_array($param)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    }

//    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8')); //构造IP
//    curl_setopt($ch, CURLOPT_REFERER, "//www.taobao.com/ "); //构造来路

    $html = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    return array(
        'info' => $info,
        'data' => $html
    );
}

function mac_list_to_tree($list, $pk='id',$pid = 'pid',$child = 'child',$root=0)
{
    $tree = array();
    if(is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }

        foreach ($list as $key => $data) {
            $parentId = $data[$pid];

            if ($root == $parentId) {
                $tree[] =& $list[$key];

            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

function arr2file($f, $arr = '')
{
    if (is_array($arr)) {
        $con = var_export($arr, true);
    } else {
        $con = $arr;
    }
    $con = "<?php\nreturn $con;\n?>";
    return write_file($f, $con);
}

function write_file($f, $c = '')
{
    $dir = dirname($f);
    if (!is_dir($dir)) {
        mkdirss($dir);
    }
    return @file_put_contents($f, $c);
}

function mkdirss($path, $mode = 0777)
{
    if (!is_dir(dirname($path))) {
        mkdirss(dirname($path));
    }
    if (!file_exists($path)) {
        return mkdir($path, $mode);
    }
    return true;
}

/**
 * 格式化文件大小
 * @param $size
 * @return string
 */
function formatSize($size)
{
    $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    if ($size == 0) {
        return ('未知');
    } else {
        return (round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
    }
}

/**
 * 生成随机数
 * @param int $length
 * @return string
 */
function make_rand($length = 8, $chars = "")
{
    if (empty($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}
